using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using BitMango.Diagnostics;

using JsonFx.Json;
using UnityEngine;

namespace BitMango
{
    public static class ControlCenter
    {
        static ControlCenter()
        {
            ControlCenter.requestParam = ControlCenter.InitParam();
            TaskManager.StartCoroutine(ControlCenter.CoRegisterFIRMessageReceived());
        }

        private static IEnumerator CoRegisterFIRMessageReceived()
        {
            while (!Platform.FinishedCheckFirebase)
            {
                yield return null;
            }
            if (Platform.CheckAndFixedFirebase)
            {
            }
            else
            {
                Debugger.Log("Can not use firebase at ControlCenter.CoRegisterFIRMessageReceived");
            }
            yield break;
        }

        private static string InitParam()
        {
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            string arg = string.Empty;
            if (Platform.Info.storeType == PlatformContext.StoreType.AppleStore)
            {
                arg = "ap";
            }
            else if (Platform.Info.storeType == PlatformContext.StoreType.GoogleStore)
            {
                arg = "go";
            }
            else if (Platform.Info.storeType == PlatformContext.StoreType.AmazonStore)
            {
                arg = "az";
            }
            else
            {
                Debugger.Assert(false, "storeType unknown : " + Platform.Info.storeType);
            }
            dictionary.Add("protocolVer", string.Format("{0}", ControlCenter.protocolVersion));
            dictionary.Add("appId", string.Format("{0}", Context.BMPlatform.appID));
            dictionary.Add("UUID", string.Format("{0}", Profile.UUID));
            dictionary.Add("aid", string.Format("{0}", Profile.ADID));
            dictionary.Add("it", string.Format("{0}", Profile.InstallTimeStr));
            dictionary.Add("iv", string.Format("{0}", Profile.InstallVersion));
            dictionary.Add("platform", string.Format("{0}", arg));
            dictionary.Add("device", string.Format("{0}", "phone"));
            return WWWBitMango.GetParametar(dictionary);
        }

        public static void GetControlCenterInfo()
        {
            if (Application.internetReachability == NetworkReachability.NotReachable)
            {
                return;
            }
            if (ControlCenter.isDataDownLoading)
            {
                Debugger.Log("ControlCenter.GetControlCenterInfo isDataDownLoading");
                return;
            }
            if (Platform.IsEU())
            {
                Profile.SetUserLv(1024);
                Debugger.Log("ControlCenter.GetControlCenterInfo set default profile for eu");
                return;
            }
            //ControlCenter.isDataDownLoading = true;
            //BitMangoRequest.GET("http://api.cc.bitmango.com/api/controlcenter.php?data=" + ControlCenter.requestParam, delegate (string json)
            //{
            //    bool flag = !string.IsNullOrEmpty(json);
            //    if (flag)
            //    {
            //        ControlCenter.data = ControlCenter.ParseControlCenterInfo(json);
            //        if (ControlCenter.data != null)
            //        {
            //            Profile.SetUserLv(ControlCenter.data.userLv);
            //            if (ControlCenter.data.message != null)
            //            {
            //                foreach (ControlCenter.Msg msg in ControlCenter.data.message)
            //                {
            //                    ControlCenter.InvokeMessageCallback(msg);
            //                }
            //            }
            //        }
            //    }
            //    ControlCenter.isDataDownLoading = false;
            //});
        }

        private static ControlCenter.Data ParseControlCenterInfo(string json)
        {
            Debugger.Assert(!string.IsNullOrEmpty(json), "ControlCenter.ParseControlCenterInfo - json is NullOrEmpty");
            ControlCenter.Data data = null;
            try
            {
                data = JsonReader.Deserialize<ControlCenter.Data>(json);
                Debugger.Assert(data != null, "ControlCenter.ParseControlCenterInfo json parse fail : " + json);
                ControlCenter.ValidateMessage(data);
            }
            catch (JsonDeserializationException ex)
            {
                Debugger.LogError("ControlCenter.ParseControlCenterInfo - JsonDeserializationException - " + ex.Message);
            }
            return data;
        }

        private static void InvokeMessageCallback(ControlCenter.Msg msg)
        {
            Debugger.Assert(msg != null);
            if (ControlCenter.OnMessageArrived != null)
            {
                ControlCenter.OnMessageArrived(msg);
            }
            else
            {
                ControlCenter.ShowAlert(msg);
            }
        }

        private static void ValidateMessage(ControlCenter.Data _data)
        {
            List<ControlCenter.Msg> list = new List<ControlCenter.Msg>();
            foreach (ControlCenter.Msg msg in _data.message)
            {
                if (string.IsNullOrEmpty(msg.item) && string.IsNullOrEmpty(msg.desc))
                {
                    Debugger.Assert(false, "ControlCenter.ValidateMessage item or desc is null");
                }
                else if (PlayerPrefs.HasKey(msg.idx))
                {
                    Debugger.Log("ControlCenter.ValidateMessage already use message - " + msg.idx);
                }
                else
                {
                    list.Add(msg);
                }
            }
            _data.message = list.ToArray();
        }

        private static void ShowAlert(ControlCenter.Msg msg)
        {
            Debugger.Assert(!string.IsNullOrEmpty(msg.item) || !string.IsNullOrEmpty(msg.desc), "ControlCenter.ShowMessage item and desc is null");
            if (string.IsNullOrEmpty(msg.item) && string.IsNullOrEmpty(msg.desc))
            {
                return;
            }
            Debugger.Log("ControlCenter.ShowMessage - " + msg.idx);
            string text = WWW.UnEscapeURL(msg.desc);
            if (!string.IsNullOrEmpty(msg.item))
            {
                try
                {
                    int num = Convert.ToInt32(msg.amount);
                    Debugger.Assert(num > 0, "ControlCenter.ShowMessage amount is Zero");
                    string text2 = string.Empty;
                    if (msg.item == "gamemoney")
                    {
                        text2 = "coin";
                    }
                    else
                    {
                        InventoryItem inventoryItemByID = Context.UncleBill.GetInventoryItemByID(msg.item);
                        Debugger.Assert(inventoryItemByID != null, "ControlCenter.Showmessage inventory item not found " + msg.item);
                        if (inventoryItemByID == null)
                        {
                            return;
                        }
                        text2 = inventoryItemByID.id;
                        if (!string.IsNullOrEmpty(inventoryItemByID.name))
                        {
                            text2 = inventoryItemByID.name;
                        }
                    }
                    text += ((!string.IsNullOrEmpty(msg.desc)) ? "\n" : string.Empty);
                    string text3 = text;
                    text = string.Concat(new object[]
                    {
                        text3,
                        text2,
                        " x ",
                        num
                    });
                }
                catch (Exception ex)
                {
                    Debugger.LogError("ControlCenter.ShowMessage " + ex.ToString());
                    return;
                }
            }
        }

        public static void UseMessage(ControlCenter.Msg msg)
        {
            Debugger.Assert(msg != null, "ControlCenter.UseMessage msg is null");
            Debugger.Log("ControlCenter.UseMessage - " + msg.idx);
            Debugger.Assert(!string.IsNullOrEmpty(msg.item) || !string.IsNullOrEmpty(msg.desc), "ControlCenter.UseMessage item or desc is null");
            if (string.IsNullOrEmpty(msg.item) && string.IsNullOrEmpty(msg.desc))
            {
                return;
            }
            if (!string.IsNullOrEmpty(msg.item))
            {
                try
                {
                    int num = Convert.ToInt32(msg.amount);
                    Debugger.Assert(num > 0, "ControlCenter.UseMessage amount is Zero");
                    if (num == 0)
                    {
                        return;
                    }
                    InventoryItem inventoryItemByID = Context.UncleBill.GetInventoryItemByID(msg.item);
                    Debugger.Assert(inventoryItemByID != null, "ControlCenter.Showmessage inventory item not found " + msg.item);
                    if (inventoryItemByID == null)
                    {
                        return;
                    }
                    Wallet.Gain(msg.item, num, "ControlCenter_" + msg.idx);
                    Wallet.Save();
                }
                catch (Exception ex)
                {
                    Debugger.LogError("ControlCenter.UseMessage " + ex.ToString());
                }
            }
            PlayerPrefs.SetInt(msg.idx, 1);
            PlayerPrefs.Save();
            if (msg.needAck == "1")
            {
                //BitMangoRequest.GET_Plain("http://api.cc.bitmango.com/api/needack.php?data=" + WWWBitMango.GetParametar(new Dictionary<string, string>
                //{
                //    {
                //        "protocolVer",
                //        string.Format("{0}", ControlCenter.protocolVersion)
                //    },
                //    {
                //        "aid",
                //        string.Format("{0}", Profile.ADID)
                //    },
                //    {
                //        "idx",
                //        string.Format("{0}", msg.idx)
                //    }
                //}), null);
            }
        }


        public static Action<ControlCenter.Msg> OnMessageArrived;

        public static ControlCenter.Data data;

        private static string protocolVersion = "2.1";

        private static string requestParam = string.Empty;

        private static bool isDataDownLoading;


        public class Data
        {
            public string protocolVer;

            public int userLv;

            public ControlCenter.Msg[] message;
        }

        public class Msg
        {
            public string idx;

            public string title;

            public string desc;

            public string item;

            public string amount;

            public string needAck;

            public string url;
        }
    }
}
